﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Navigation;
using Facebook;
using QuizzMe.Helpers;

namespace QuizzMe
{
    /// <summary>
    /// Main page
    /// </summary>
    public partial class MainPage : UserControl, INotifyPropertyChanged
    {
        private BasePage _currentPage;
        private Fb _fb;
        private string id;

        /// <summary>
        /// Title of current page
        /// </summary>
        public String PageTitle
        {
            get { return _currentPage == null ? string.Empty : _currentPage.PageTitle; }
        }

        /// <summary>
        /// User total score
        /// </summary>
        public int Score
        {
            get
            {
                return AuthHelper.Get.CurrentUser == null ? 0 : AuthHelper.Get.CurrentUser.User.score;
            }
        }

        /// <summary>
        /// User rank
        /// </summary>
        public int Rank
        {
            get
            {
                return AuthHelper.Get.CurrentUser == null ? 0 : AuthHelper.Get.CurrentUser.Rank;
            }
        }

        /// <summary>
        /// User difficulty
        /// </summary>
        public String Difficulty
        {
            get { return (AuthHelper.Get.CurrentUser == null || AuthHelper.Get.CurrentUser.User.Difficulty == null) ? "N.C" : AuthHelper.Get.CurrentUser.User.Difficulty.name; }
        }

        /// <summary>
        /// User avatar (short picture)
        /// </summary>
        public String UserAvatar
        {
            get { return AuthHelper.Get.CurrentUser == null ? "http://2.bp.blogspot.com/_qiWDwsGO5NE/TFVr1qkw7eI/AAAAAAAAAtg/afTYTMBpZjk/s1600/tricia_helfer.jpg" : AuthHelper.Get.CurrentUser.Avatar; }
        }

        /// <summary>
        /// Is the current user logged ?
        /// </summary>
        public bool UserLogged
        {
            get { return AuthHelper.Get.CurrentUser != null; }
        }

        /// <summary>
        /// Loading in progress ? (show / hide the loading panel)
        /// </summary>
        public bool Loading
        {
            get { return _currentPage == null ? false : _currentPage.Loading; }
            set
            {
                if (_currentPage != null)
                    _currentPage.Loading = value;
            }
        }

        public MainPage()
        {
            InitializeComponent();

            ServiceClientHelper.Client.GetRankCompleted += ClientGetRankCompleted;

            HtmlPage.RegisterScriptableObject("slObject", this);
            AuthHelper.LoginToFbViaJs();
        }

        private void ContentFrameNavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            Debug.WriteLine("Navigation failed");
        }

        private void ContentFrameNavigated(object sender, NavigationEventArgs e)
        {
            _currentPage = (BasePage)e.Content;

            if (_currentPage != null)
            {
                _currentPage.PropertyChanged -= OnPagePropertyChanged;
                _currentPage.PropertyChanged += OnPagePropertyChanged;
            }

            RefreshDynamicInfos();

            if (!UserLogged)
                Loading = true;
        }

        /// <summary>
        /// Refresh dynamic data
        /// </summary>
        public void RefreshDynamicInfos()
        {
            OnPropertyChanged("PageTitle");
            OnPropertyChanged("Loading");
            OnPropertyChanged("Score");
            OnPropertyChanged("Difficulty");
            OnPropertyChanged("UserAvatar");
            OnPropertyChanged("UserLogged");

            if (AuthHelper.Get.CurrentUser != null)
                ServiceClientHelper.Client.GetRankAsync(AuthHelper.Get.CurrentUser.User.userId);
        }

        protected void ClientGetRankCompleted(object sender, QuizzServiceRef.GetRankCompletedEventArgs e)
        {
            if (AuthHelper.Get.CurrentUser != null)
                AuthHelper.Get.CurrentUser.Rank = e.Result.Position;

            OnPropertyChanged("Rank");
        }

        // INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(string element)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(element));
        }

        private void OnPagePropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, e);
        }


        [ScriptableMember]
        public void LoginComplete(string accesstoken, string errorDescription)
        {
            if (string.IsNullOrEmpty(errorDescription) && !string.IsNullOrEmpty(accesstoken))
            {
                // we have access token.
                AuthHelper.Get.SetFacebookClient(new FacebookClient(accesstoken));
                _fb = AuthHelper.Get.FacebookClient;

                loginSucceeded();
            }
            else
            {
                HtmlPage.Window.Alert(errorDescription);
            }
        }

        [ScriptableMember]
        public void SetText(string text)
        {
            var Parameters = new Dictionary<string, string>();
            try
            {
                var sp = text.Split(new[] { "?", "#" }, StringSplitOptions.RemoveEmptyEntries);
                if (sp.Length == 1)
                    return;
                var pairs = sp[1].Split(new[] { "&" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var pair in pairs)
                {
                    var splPair = pair.Split(new[] { "=" }, StringSplitOptions.RemoveEmptyEntries);
                    if (splPair.Length >= 2)
                        Parameters[splPair[0]] = splPair[1];
                }
            }
            finally
            {
                AuthHelper.Get.Params = Parameters;
            }
        }

        private void loginSucceeded()
        {
            // FbLoginButton.Visibility = Visibility.Collapsed;

            _fb.AddHandler(OnFbOnGetCompleted);
            //fb.GetCompleted += OnFbOnGetCompleted;
            _fb.QueryAsync(String.Format("SELECT name, email, pic, uid FROM user WHERE uid=me()", id));
        }

        private void OnFbOnGetCompleted(object s, FacebookApiEventArgs ee)
        {
            //fb.GetCompleted -= OnFbOnGetCompleted;
            var arr = (JsonArray)ee.GetResultData();
            var result2 = (IDictionary<string, object>)arr[0];
            int i = 0;
            AuthHelper.Get.Login((string)result2["uid"], result2, delegate
                                                                       {
                                                                           Dispatcher.BeginInvoke(() =>
                                                                                                      {
                                                                                                          RefreshDynamicInfos();
                                                                                                          Loading = false;
                                                                                                      });
                                                                       });
        }
    }
}